<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="vehcusunitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" />
      <el-table-column label="订单类型" align="center" prop="orderType">
        <template slot-scope="{row: {orderType}}">
          <span v-if="+orderType === 1">虚拟订单</span>
          <span v-else-if="+orderType === 2">平台订单</span>
        </template>
      </el-table-column>
      <el-table-column label="租车类型" align="center" prop="carType" >
        <template slot-scope="{row: {carType}}">
          <span v-if="+carType === 1">租车</span>
          <span v-else-if="+carType === 2">包车</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="结算类型" align="center" prop="settleType" >
        <template slot-scope="{row: {carType}}">
          <span v-if="+carType === 1">报销</span>
          <span v-else-if="+carType === 2">提成</span>
          <span v-else-if="+carType === 3">收入</span>
          <span v-else-if="+carType === 4">外调</span>
        </template>
      </el-table-column>
      <el-table-column label="原因" align="center" prop="reason" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改商户单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-input v-show="false" v-model="form.id"></el-input>
        <el-form-item label="企业全称" prop="customerUnitName" v-if="isShowCompany">
          <el-input v-model="form.customerUnitName" placeholder="请输入企业全称" />
        </el-form-item>
        <el-form-item label="法人姓名" prop="comContactName" v-if="isShowCompany">
          <el-input v-model="form.comContactName" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="法人身份证" prop="comContactIdCard" v-if="isShowCompany">
          <el-input v-model="form.comContactIdCard" placeholder="请输入法人身份证" />
        </el-form-item>
        <el-form-item label="法人地址" prop="comContactAddr" v-if="isShowCompany">
          <el-input v-model="form.comContactAddr" placeholder="请输入法人地址" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="socialCreditCode" v-if="isShowCompany">
          <el-input v-model="form.socialCreditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="注册时间" prop="regTime" v-if="isShowCompany">
          <el-date-picker clearable
                          v-model="form.regTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择注册时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="企业地址" prop="comAddress" v-if="isShowCompany">
          <el-input v-model="form.comAddress" placeholder="请输入企业地址" />
        </el-form-item>
        <el-form-item label="企业邮箱" prop="comEmail" v-if="isShowCompany">
          <el-input v-model="form.comEmail" placeholder="请输入企业邮箱" />
        </el-form-item>
        <el-form-item label="注册资金" prop="regAmount" v-if="isShowCompany">
          <el-input v-model="form.regAmount" placeholder="请输入注册资金" />
        </el-form-item>
        <el-form-item label="微信商户号" prop="merchantId" v-if="isShowCompany">
          <el-input v-model="form.merchantId" placeholder="请输入微信商户号" />
        </el-form-item>
        <el-form-item label="银行开户支行" prop="openingBank" v-if="isShowCompany">
          <el-input v-model="form.openingBank" placeholder="请输入银行开户支行" />
        </el-form-item>
        <el-form-item label="银行账户" prop="bankAccount" v-if="isShowCompany">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账户" />
        </el-form-item>
        <el-form-item label="工商营业执照" prop="compics" v-if="isShowCompany">
          <input type="file" @change="handleFileUpload" multiple />
          <div>
            请上传最新的营业执照，格式要求:原件照片、扫描件或者加盖公章的复印件，支持,jpg
            jpeg .bmp .gifpng格式照片，大小不超过10M。
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listVehcusunit,getVehcusunit, delVehcusunit, addVehcusunit, updateVehcusunit} from "@/api/merunit/vehmerunit"
import {systemuseruploadfiles, sysusercarduploadfiles} from "@/api/system/user";
import {addExpinfo, delExpinfo, listExpinfo, updateExpinfo} from "@/api/expressinfo/expinfo";
import store from "@/store";
export default {
  name: "Vehcusunit",
  dicts: ['order_unit_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isShowPerson: true,
      isShowCompany: false,
      // 总条数
      total: 0,
      // 商户单位表格数据
      vehcusunitList: [],
      // 快递地址表格数据
      expinfoList: [],
      infomation: {
        infolist: [{ id: "",name: "", expressAddr: "", telephone: "" }],
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        financeType: null,
        orderId: null
      },
      // 表单参数
      form: {},
      expressForm: {},
      queryExpressForm: {},
      // 表单校验
      rules: {
        customerUnitName: [
          { required: true, message: "企业全称不能为空", trigger: "blur" }
        ],
        comContactName: [
          { required: true, message: "法人姓名不能为空", trigger: "blur" }
        ],
        comContactIdCard: [
          { required: true, message: "法人身份证不能为空", trigger: "blur" }
        ],
        comContactAddr: [
          { required: true, message: "法人地址不能为空", trigger: "blur" }
        ],

        socialCreditCode: [
          { required: true, message: "统一社会信用代码不能为空", trigger: "blur" }
        ],
        comAddress: [
          { required: true, message: "企业地址不能为空", trigger: "blur" }
        ],
        comEmail: [
          { required: true, message: "企业邮箱不能为空", trigger: "blur" }
        ],
        regAmount: [
          { required: true, message: "注册资金不能为空", trigger: "blur" }
        ],
        regTime: [
          { required: true, message: "注册时间不能为空", trigger: "blur" }
        ],
        merchantId: [
          { required: true, message: "微信商户号不能为空", trigger: "blur" }
        ],
        openingBank: [
          { required: true, message: "银行开户支行不能为空", trigger: "blur" }
        ],
        bankAccount: [
          { required: true, message: "银行账户不能为空", trigger: "blur" }
        ],
        compics: [
          { required: true, message: "工商营业执照不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商户单位列表 */
    getList() {
      this.loading = true;
      this.queryParams.financeType = 2
      listVehcusunit(this.queryParams).then(response => {
        this.vehcusunitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    addItem() {
      let that = this;
      var index;
      for(var i=0;i<this.infomation.infolist.length;i++){
        this.expressForm.name=that.infomation.infolist[i].name;
        this.expressForm.expressAddr=that.infomation.infolist[i].expressAddr;
        this.expressForm.telephone=that.infomation.infolist[i].telephone;
        index=i;
      }
      this.expressForm.userId=store.getters.userId;
      this.expressForm.expressType=2;
      this.expressForm.id=null;
      if(this.form.id!=null){
        this.expressForm.cusUnitId=this.form.id;
      }
      addExpinfo(this.expressForm).then(response => {
        this.$modal.msgSuccess("新增成功")
        that.infomation.infolist[index].id=response.expressId;
      });
      that.infomation.infolist.push({
        id: "",
        name: "",
        expressAddr: "",
        telephone: "",
      });
    },

    deleteItem(i) {
      if (this.infomation.infolist.length <= 1) {
        return false;
      }
      console.log(this.infomation.infolist[i].name+this.infomation.infolist[i].expressAddr+this.infomation.infolist[i].telephone);
      if(this.infomation.infolist[i].id!='') {
        delExpinfo(this.infomation.infolist[i].id).then(response => {
          this.$modal.msgSuccess("删除成功");
        })
      }
      this.infomation.infolist.splice(i, 1);

    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerUnitName: null,
        comContactName: null,
        comContactIdCard: null,
        comContactAddr: null,
        addTime: null,
        socialCreditCode: null,
        regTime: null,
        comAddress: null,
        comEmail: null,
        regAmount: null,
        merchantId: null,
        openingBank: null,
        bankAccount: null,
        compics: null,
        personName: null,
        personTel: null,
        personEmail: null,
        personAddr: null,
        expressAddr: null,
        unitType: null,
        personIdCard: null,
        personpics: null
      };
      this.resetForm("form");
    },
    handleChange(value) {
      if(value==0){
        this.isShowPerson=true;
        this.isShowCompany=false;
      }else{
        this.isShowPerson=false;
        this.isShowCompany=true;
      }
      if(this.form.id==null || this.form.id=='') {
        this.form.customerUnitName = '';
        this.form.comContactName = '';
        this.form.comContactIdCard = '';
        this.form.comContactAddr = '';
        this.form.socialCreditCode = '';
        this.form.regTime = '';
        this.form.comAddress = '';
        this.form.comEmail = '';
        this.form.regAmount = '';
        this.form.merchantId = '';
        this.form.openingBank = '';
        this.form.bankAccount = '';
        this.form.personName = '';
        this.form.personTel = '';
        this.form.personEmail = '';
        this.form.personAddr = '';
        this.form.expressAddr = '';
        this.form.personIdCard = '';
        this.form.compics = '';
        this.form.personpics = '';
      }
    },
    handleFileUpload(event) {
      // 获取用户选择的文件
      console.log(event);
      // 创建 FormData 对象
      // 将选定的文件存储到 selectedFiles 数组中
      let selectedFiles = Array.from(event.target.files);

      // 将 selectedFiles 数组中的文件上传到后端服务器
      const formData = new FormData();
      selectedFiles.forEach((file) => {
        formData.append("files", file);
      });
      console.log(formData);
      // return;
      // 发送 POST 请求上传图片
      systemuseruploadfiles(formData).then((res) => {
        console.log(res);
        this.form.compics = res.urls;
      });
    },
    handleCardFileUpload(event) {
      // 获取用户选择的文件
      console.log(event);
      // 创建 FormData 对象
      // 将选定的文件存储到 selectedFiles 数组中
      let selectedFiles = Array.from(event.target.files);

      // 将 selectedFiles 数组中的文件上传到后端服务器
      const formData = new FormData();
      selectedFiles.forEach((file) => {
        formData.append("files", file);
      });
      console.log(formData);
      // return;
      // 发送 POST 请求上传图片
      sysusercarduploadfiles(formData).then((res) => {
        console.log(res);
        this.form.personpics = res.urls;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.unitType=0;
      this.open = true;
      this.infomation.infolist=[];
      this.infomation.infolist.push({
        id: "",
        name: "",
        expressAddr: "",
        telephone: "",
      });
      this.title = "添加商户单位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if(row.unitType==0){
        this.isShowPerson=true;
        this.isShowCompany=false;
      }else{
        this.isShowPerson=false;
        this.isShowCompany=true;
      }
      const id = row.id || this.ids
      getVehcusunit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "认证商户单位";
      });
      this.infomation.infolist=[];
      this.queryExpressForm.cusUnitId=id;
      listExpinfo(this.queryExpressForm).then(response => {
        this.expinfoList = response.rows;
        if(this.expinfoList.length>0) {
          for (var i = 0; i < this.expinfoList.length; i++) {
            this.infomation.infolist.push({
              id: this.expinfoList[i].id,
              name: this.expinfoList[i].name,
              expressAddr: this.expinfoList[i].expressAddr,
              telephone: this.expinfoList[i].telephone,
            });
          }
        }else{
          this.infomation.infolist.push({
            id: "",
            name: "",
            expressAddr: "",
            telephone: "",
          });
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVehcusunit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              for(var i=0;i<this.infomation.infolist.length;i++){
                if(this.infomation.infolist[i].name!='' || this.infomation.infolist[i].expressAddr!=''  || this.infomation.infolist[i].telephone!='') {
                  this.expressForm.cusUnitId = this.form.id;
                  this.expressForm.id = this.infomation.infolist[i].id;
                  updateExpinfo(this.expressForm).then(response => {

                  });
                }
              }
              this.open = false;
              this.getList();
            });
          } else {
            addVehcusunit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              for(var i=0;i<this.infomation.infolist.length;i++){
                if(this.infomation.infolist[i].name!='' || this.infomation.infolist[i].expressAddr!=''  || this.infomation.infolist[i].telephone!='') {
                  this.expressForm.cusUnitId = response.cusUnitId;
                  this.expressForm.id = this.infomation.infolist[i].id;
                  updateExpinfo(this.expressForm).then(response => {

                  });
                }
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据项？').then(function() {
        return delVehcusunit(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cusunit/vehcusunit/export', {
        ...this.queryParams
      }, `vehcusunit_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
